﻿using System.Threading.Tasks;
using Colorful.Furniture.UserManagement;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using Volo.Abp;
using Volo.Abp.Application.Services;
using UserAppService = Colorful.Furniture.UserManagement.UserAppService;

namespace Colorful.Furniture.MiniProgram;

/// <summary>
///  微信小程序用户
/// </summary>
public class WechatMiniUserAppService : ApplicationService
{
    private readonly IWechatMiniProgramExtensions _wechatMiniProgramExtensions;
    private readonly ILogger<WechatMiniUserAppService> _logger;
    private readonly UserAppService _userAppService;

    public WechatMiniUserAppService(
        IWechatMiniProgramExtensions wechatMiniProgramExtensions,
        ILogger<WechatMiniUserAppService> logger,
        UserAppService userAppService)
    {
        _wechatMiniProgramExtensions = wechatMiniProgramExtensions;
        _logger = logger;
        _userAppService = userAppService;
    }

    /// <summary>
    ///  通过微信小程序获取的电话号码登录
    /// </summary>
    /// <remarks>该接口需配合手机号快速验证或手机号实时验证能力一起使用，当用户同意后，可以通过 bindgetphonenumber 或 bindrealtimegetphonenumber 事件回调获取到动态令牌code，再调用该接口将code换取用户手机号。</remarks>
    /// <returns></returns>
    [RemoteService(IsEnabled = false)]
    public async Task<string> GetPhoneNumberAsync(string code)
    {
        var phoneNumberApiResult = await _wechatMiniProgramExtensions.Client.ExecuteWxaBusinessGetUserPhoneNumberAsync(
            new WxaBusinessGetUserPhoneNumberRequest
            {
                AccessToken = await _wechatMiniProgramExtensions.GetAccessTokenAsync(),
                Code = code
            });

        _wechatMiniProgramExtensions.HandleWxJsonResult(phoneNumberApiResult);

        return phoneNumberApiResult.PhoneInfo.PhoneNumber;
    }

    /// <summary>
    ///  微信公众号用户登录
    /// </summary>
    /// <returns></returns>
    [RemoteService(IsEnabled = false)]
    public async Task<string> LoginAsync(string code, string nickName, string headImg)
    {
        //通过微信公众号授权code获取用户编码
        var openId = await GetOpenIdAsync(code);

        ////用户编码
        //var userId = await _userAppService.CreateOrUpdateAsync(new CreateOrUpdateUserInputDto
        //{
        //    Identifier = nickName,
        //    Credential = openId,
        //    HeadImageUrl = headImg,
        //    IdentityType = IdentityType.微信小程序
        //});

        //_logger.LogInformation($"写入到用户申明的中的用户编码为:{userId}");

        //return _userAppService.GenerateUserToken(userId);

        return "";
    }

    /// <summary>
    ///  通过 wx.login 接口获得临时登录凭证 code 获取用户id和openId
    /// </summary>
    /// <param name="code"></param>
    /// <returns>item1 用户编码；item2:微信公众号授权回调返回的用户信息</returns>
    [RemoteService(IsEnabled = false)]
    public async Task<string> GetOpenIdAsync(string code)
    {
        if (string.IsNullOrWhiteSpace(code))
            throw new UserFriendlyException("请传入微信小程序登录凭证");

        //获取用户接口访问凭证信息
        var wxResult = await _wechatMiniProgramExtensions.Client.ExecuteSnsJsCode2SessionAsync(new SnsJsCode2SessionRequest
        {
            AccessToken = await _wechatMiniProgramExtensions.GetAccessTokenAsync(),
            JsCode = code
        });

        _wechatMiniProgramExtensions.HandleWxJsonResult(wxResult);

        _logger.LogInformation($"获取到微信授权用户信息为:{JsonConvert.SerializeObject(wxResult)}");


        return wxResult.OpenId;
    }
}